package com.mrd.gtimp.business.action;

import com.mrd.base.Jqgrid;
import com.mrd.constant.MsgConstants;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.business.entity.Commodity;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.entity.InspectionGoods;
import com.mrd.gtimp.business.entity.InspectionGoodsDetails;
import com.mrd.gtimp.business.service.CommodityBiz;
import com.mrd.gtimp.business.service.DeclarationBiz;
import com.mrd.gtimp.business.service.InspectionGoodsBiz;
import com.mrd.util.LoginUtil;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

/**
 * Created by lenovo on 2016/9/18.
 */
@Controller
@RequestMapping("/inspectionGoods")
public class InspectionGoodsAction {

    /**
     * 日志
     */
    private static final Logger logger = Logger
            .getLogger(InspectionGoodsAction.class);

    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Resource
    private InspectionGoodsBiz inspectionGoodsBiz;

    @Resource
    private DeclarationBiz declarationBiz;

    @Resource
    private CommodityBiz commodityBiz;

    @RequestMapping("/main")
    public String main(Model model) {
        String comType = LoginUtil.getLoginUser().getCompany().getType();
        model.addAttribute("comType", comType);
        return "/gtimp3/inspectionGoods/main";
    }

    @RequestMapping("/viewPage")
    public String viewPage(Model model, String declarationId, String inspectionId) {
        try {
            Declaration declaration = null;
            if (StringUtils.isNotEmpty(inspectionId)) {
                InspectionGoods inspectionGoods = inspectionGoodsBiz.findEntityById(inspectionId);
                if (inspectionGoods != null) {
                    Commodity commodity = inspectionGoods.getInspectionCommodity();
                    model.addAttribute("commodity", commodity);
                    List<InspectionGoodsDetails> inspectionGoodsDetailsList = inspectionGoods
                            .getInspectionGoodsDetailsList();
                    if (inspectionGoodsDetailsList != null
                            && inspectionGoodsDetailsList.size() > 0) {
                        StringBuilder inspectionContent = new StringBuilder();
                        for (InspectionGoodsDetails inspectionGoodsDetails : inspectionGoodsDetailsList) {
                            inspectionContent.append("查验时间：")
                                    .append(simpleDateFormat
                                            .format(inspectionGoodsDetails.getCreateTime()))
                                    .append("\n");
                            inspectionContent.append("实施查验单位：").append((StringUtils
                                    .isNotEmpty(inspectionGoodsDetails.getInspectionCompany())
                                    && inspectionGoodsDetails.getInspectionCompany().equals("其他"))
                                    ? inspectionGoodsDetails.getInspectionExt()
                                    : inspectionGoodsDetails.getInspectionCompany())
                                    .append("\n");
                            inspectionContent.append("查验项目：")
                                    .append(inspectionGoodsDetails.getInspectionProject())
                                    .append("\n");
                            inspectionContent.append("查验情况：")
                                    .append(inspectionGoodsDetails.getInspectionSituation())
                                    .append("\n");
                            inspectionContent.append("------------------------------------\n");
                        }
                        model.addAttribute("inspectionContent", inspectionContent);
                    }
                    model.addAttribute("inspectionGoods", inspectionGoods);
                    declaration = inspectionGoods.getDeclaration();
                }
            }
            if (StringUtils.isNotEmpty(declarationId) && declaration == null) {
                declaration = declarationBiz.findEntityById(declarationId);
            }
            if (declaration != null) {
                model.addAttribute("declaration", declaration);
            }
        } catch (Exception e) {
            logger.error("InspectionGoodsAction.updatePage error!declarationId=" + declarationId
                    + ",inspectionId=" + inspectionId);
            e.printStackTrace();
        }
        return "/gtimp3/inspectionGoods/view";
    }

    @RequestMapping("/addPage")
    public String addPage(Model model, String declarationId, String containerNo,
                          String inspectionCommodityId) {
        try {
            if (StringUtils.isEmpty(declarationId) || StringUtils.isEmpty(containerNo)
                    || StringUtils.isEmpty(inspectionCommodityId)) {
                logger.error("InspectionGoodsAction.addPage error!declarationId=" + declarationId
                        + ",containerNo=" + containerNo + ",inspectionCommodityId="
                        + inspectionCommodityId);
                throw new Exception("InspectionGoodsAction.addPage error!declarationId="
                        + declarationId + ",containerNo=" + containerNo + ",inspectionCommodityId="
                        + inspectionCommodityId);
            } else {
                Declaration declaration = declarationBiz.findEntityById(declarationId);
                Commodity commodity = commodityBiz.findEntityById(inspectionCommodityId);
                model.addAttribute("declaration", declaration);
                model.addAttribute("containerNo", containerNo);
                model.addAttribute("commodity", commodity);

                Jqgrid jqgrid = new Jqgrid();
                jqgrid.addRule(new SearchRule("declaration.id", SearchRuleOption.eq, declarationId));
                jqgrid.addRule(new SearchRule("containerNo", SearchRuleOption.eq, containerNo));
                jqgrid.addRule(new SearchRule("inspectionCommodity.id", SearchRuleOption.eq, inspectionCommodityId));
                Page<InspectionGoods> inspectionGoodsPage = inspectionGoodsBiz.findByJqgrid(jqgrid);
                if (inspectionGoodsPage != null) {
                    List<InspectionGoods> inspectionGoodsList = inspectionGoodsPage.getContent();
                    if (inspectionGoodsList != null && inspectionGoodsList.size() == 1) {
                        InspectionGoods inspectionGoods = inspectionGoodsList.get(0);
                        model.addAttribute("inspectionGoods", inspectionGoods);
                        List<InspectionGoodsDetails> inspectionGoodsDetailsList = inspectionGoods
                                .getInspectionGoodsDetailsList();
                        if (inspectionGoodsDetailsList != null
                                && inspectionGoodsDetailsList.size() > 0) {
                            StringBuilder inspectionContent = new StringBuilder();
                            for (InspectionGoodsDetails inspectionGoodsDetails : inspectionGoodsDetailsList) {
                                inspectionContent.append("查验时间：")
                                        .append(simpleDateFormat
                                                .format(inspectionGoodsDetails.getCreateTime()))
                                        .append("\n");
                                inspectionContent.append("实施查验单位：")
                                        .append((StringUtils
                                                .isNotEmpty(inspectionGoodsDetails
                                                        .getInspectionCompany())
                                                && inspectionGoodsDetails.getInspectionCompany()
                                                .equals("其他"))
                                                ? inspectionGoodsDetails
                                                .getInspectionExt()
                                                : inspectionGoodsDetails
                                                .getInspectionCompany())
                                        .append("\n");
                                inspectionContent.append("查验项目：")
                                        .append(inspectionGoodsDetails.getInspectionProject())
                                        .append("\n");
                                inspectionContent.append("查验情况：")
                                        .append(inspectionGoodsDetails.getInspectionSituation())
                                        .append("\n");
                                inspectionContent.append("------------------------------------\n");
                            }
                            model.addAttribute("inspectionContent", inspectionContent);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/gtimp3/inspectionGoods/update";
    }

    @RequestMapping("/updatePage")
    public String updatePage(Model model, String declarationId, String inspectionId) {
        try {
            Declaration declaration = null;
            if (StringUtils.isNotEmpty(inspectionId)) {
                InspectionGoods inspectionGoods = inspectionGoodsBiz.findEntityById(inspectionId);
                if (inspectionGoods != null) {
                    Commodity commodity = inspectionGoods.getInspectionCommodity();
                    model.addAttribute("commodity", commodity);
                    List<InspectionGoodsDetails> inspectionGoodsDetailsList = inspectionGoods
                            .getInspectionGoodsDetailsList();
                    if (inspectionGoodsDetailsList != null
                            && inspectionGoodsDetailsList.size() > 0) {
                        StringBuilder inspectionContent = new StringBuilder();
                        for (InspectionGoodsDetails inspectionGoodsDetails : inspectionGoodsDetailsList) {
                            inspectionContent.append("查验时间：")
                                    .append(simpleDateFormat
                                            .format(inspectionGoodsDetails.getCreateTime()))
                                    .append("\n");
                            inspectionContent.append("实施查验单位：").append((StringUtils
                                    .isNotEmpty(inspectionGoodsDetails.getInspectionCompany())
                                    && inspectionGoodsDetails.getInspectionCompany().equals("其他"))
                                    ? inspectionGoodsDetails.getInspectionExt()
                                    : inspectionGoodsDetails.getInspectionCompany())
                                    .append("\n");
                            inspectionContent.append("查验项目：")
                                    .append(inspectionGoodsDetails.getInspectionProject())
                                    .append("\n");
                            inspectionContent.append("查验情况：")
                                    .append(inspectionGoodsDetails.getInspectionSituation())
                                    .append("\n");
                            inspectionContent.append("------------------------------------\n");
                        }
                        model.addAttribute("inspectionContent", inspectionContent);
                    }
                    model.addAttribute("inspectionGoods", inspectionGoods);
                    declaration = inspectionGoods.getDeclaration();
                }
            }
            if (StringUtils.isNotEmpty(declarationId) && declaration == null) {
                declaration = declarationBiz.findEntityById(declarationId);
            }
            if (declaration != null) {
                model.addAttribute("declaration", declaration);
            }
        } catch (Exception e) {
            logger.error("InspectionGoodsAction.updatePage error!declarationId=" + declarationId
                    + ",inspectionId=" + inspectionId);
            e.printStackTrace();
        }
        return "/gtimp3/inspectionGoods/update";
    }

    @RequestMapping("/doUpdateInfo")
    @ResponseBody
    public Result doUpdateInfo(String inspectionId, String container_no, String declarationId,
                               String inspection_time, String inspection_company, String inspection_ext_company,
                               String inspection_project, String inspection_situation, String inspectionCommodityId) {
        if (StringUtils.isEmpty(inspectionId) && (StringUtils.isEmpty(declarationId)
                || StringUtils.isEmpty(inspectionCommodityId))) {
            logger.error("InspectionGoodsAction.doUpdateInfo fail!inspectionId=" + inspectionId
                    + ",declarationId=" + declarationId + ",inspectionCommodityId="
                    + inspectionCommodityId);
            return Result.newFailInstance(MsgConstants.SAVE_FAIL);
        }
        if (StringUtils.isEmpty(container_no) || StringUtils.isEmpty(inspection_time)
                || StringUtils.isEmpty(inspection_company)
                || StringUtils.isEmpty(inspection_project)
                || StringUtils.isEmpty(inspection_situation)) {
            logger.error("InspectionGoodsAction.doUpdateInfo fail!container_no=" + container_no
                    + ",inspection_time=" + inspection_time + ",inspection_company="
                    + inspection_company + ",inspection_project=" + inspection_project
                    + ",inspection_situation=" + inspection_situation);
            return Result.newFailInstance(MsgConstants.SAVE_FAIL);
        }
        User user = LoginUtil.getLoginUser();
        try {
            InspectionGoods inspectionGoods = new InspectionGoods();
            if (StringUtils.isNotEmpty(inspectionId)) {
                inspectionGoods = inspectionGoodsBiz.findEntityById(inspectionId);
            } else {
                inspectionGoods.setId(null);
                inspectionGoods.setContainerNo(container_no);
                Commodity commodity = commodityBiz.findEntityById(inspectionCommodityId);
                inspectionGoods.setInspectionCommodity(commodity);
                Declaration declaration = declarationBiz.findEntityById(declarationId);
                declaration.setState(Declaration.DeclarationBusinessState.CUSTOM_CHECK);
                inspectionGoods.setDeclaration(declaration);
                inspectionGoods.setCreateTime(new Date());
                inspectionGoods.setState("1");
            }
            List<InspectionGoodsDetails> inspectionGoodsDetailsList = new ArrayList<>();
            InspectionGoodsDetails inspectionGoodsDetails = new InspectionGoodsDetails();
            inspectionGoodsDetails.setId(null);
            inspectionGoodsDetails.setInspectionGoods(inspectionGoods);
            inspectionGoodsDetails.setCreateTime(simpleDateFormat.parse(inspection_time));
            inspectionGoodsDetails.setInspectionCompany(inspection_company);
            inspectionGoodsDetails.setInspectionExt(inspection_ext_company);
            inspectionGoodsDetails.setInspectionProject(inspection_project);
            inspectionGoodsDetails.setInspectionSituation(inspection_situation);
            inspectionGoodsDetails.setCreator(user);
            inspectionGoodsDetailsList.add(inspectionGoodsDetails);
            inspectionGoods.setInspectionGoodsDetailsList(inspectionGoodsDetailsList);
            inspectionGoodsBiz.saveOrupdateEntity(inspectionGoods);
            return Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.newFailInstance(MsgConstants.SAVE_FAIL);
    }

    @RequestMapping("/findInspectionGoodsList")
    @ResponseBody
    public Page<Map<String, Object>> findInspectionGoodsList(Jqgrid jqgrid) {
        Map<String, Object> params = jqgrid.getFilterMap();
        if (params.size() == 0) {
            jqgrid.addRule(new SearchRule("state", SearchRuleOption.eq, "0"));
        } else if (params.get("state") != null){
            //处理多种放行状态
            Object stateO = params.get("state");
            if(stateO != null && stateO.toString().length() > 1){
                String deptCode = "DEPT_OTHER";
                switch (stateO.toString()){
                    case "14":
                        deptCode = "DEPT_CUSTOM";
                        break;
                    case "15":
                        deptCode = "DEPT_COMMODITY";
                        break;
                    case "16":
                    default:
                }
                params.remove("state");
                params.put("deptCode", deptCode);
            }
        }

        String companyId = LoginUtil.getLoginUser().getCompany().getId();
        try {
            //分页
            jqgrid.pageWithMybatis();
            //组装查询条件
            if (!LoginUtil.getLoginUser().getCompany().getName().equals("佛山市佛航展翔物流有限公司") || !LoginUtil.getLoginUser().getType().equals("0")) {
                jqgrid.addRule(new SearchRule("supId", SearchRuleOption.eq, companyId));
                params.put("supId", companyId);
            }
            //排序
            jqgrid.sortWithMybatis();
            return inspectionGoodsBiz.listPageData(jqgrid.getPage(), params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*old
    @RequestMapping("/findInspectionGoodsList")
    @ResponseBody
    @Json({@JField("id"), @JField("declaration.id"), @JField("createTime"), @JField("containerNo"),
            @JField("declaration.businessId"), @JField("declaration.sno"),
            @JField("declaration.shipper.name"), @JField("declaration.company_name"),
            @JField("inspectionCompanyProject"), @JField("declaration.declaration_type"),
            @JField("state"), @JField("inspectionCommodity.name"), @JField("declaration.state"),
            @JField("inspectionCommodity.goods_mode")})
    public Page<InspectionGoods> findInspectionGoodsList(Jqgrid jqgrid) {
        if (jqgrid.getFilters() == null) {
            jqgrid.addRule(new SearchRule("state", SearchRuleOption.eq, "1"));
        }
        if (!LoginUtil.getLoginUser().getCompany().getName().equals("佛山市佛航展翔物流有限公司") || !LoginUtil.getLoginUser().getType().equals("0")) {
            String companyId = LoginUtil.getLoginUser().getCompany().getId();
            jqgrid.addRule(new SearchRule("declaration.supCompany.id", SearchRuleOption.eq, companyId));
        }
        try {
            Page<InspectionGoods> inspectionGoodsPage = inspectionGoodsBiz.findByJqgrid(jqgrid);
            List<InspectionGoods> inspectionGoodsList = inspectionGoodsPage.getContent();
            Map<String, String> map = this.getInspectionCompanyProject(inspectionGoodsList);
            inspectionGoodsList.stream().forEach(inspectionGoods -> inspectionGoods
                    .setInspectionCompanyProject(map.get(inspectionGoods.getId())));
            inspectionGoodsPage = new PageImpl<>(inspectionGoodsList, jqgrid
                    .getPage(), inspectionGoodsPage.getTotalPages());
            return inspectionGoodsPage;
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return null;
    }*/

    private Map<String, String> getInspectionCompanyProject(
            List<InspectionGoods> inspectionGoodsList) {
        Map<String, String> map = new HashMap<>();
        for (InspectionGoods inspectionGoods : inspectionGoodsList) {
            List<InspectionGoodsDetails> inspectionGoodsDetailsList = inspectionGoods
                    .getInspectionGoodsDetailsList();
            String inspectionCompanyProject = "";
            for (InspectionGoodsDetails inspectionGoodsDetails : inspectionGoodsDetailsList) {
                String inspectionCompany = inspectionGoodsDetails.getInspectionCompany();
                if (StringUtils.isNotEmpty(inspectionCompany) && inspectionCompany.equals("其他")) {
                    inspectionCompany += "-" + inspectionGoodsDetails.getInspectionExt();
                }
                inspectionCompanyProject += "查验单位：" + inspectionCompany + ",查验项目："
                        + inspectionGoodsDetails.getInspectionProject() + "\n";
            }
            map.put(inspectionGoods.getId(), inspectionCompanyProject);
        }
        return map;
    }
}
